import { UserOutlined, DesktopOutlined} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Avatar, Button, Card, Divider, Modal, Form, Input, Select, message,Upload,Image } from 'antd'
import React, { memo, useEffect, useState } from 'react'
import '../css/mprofile.css'
// 获取redux
import { useSelector, useDispatch } from 'react-redux'


import { getUserInfo, updateUserInfo } from '../../../api/profile'
import dayjs from 'dayjs'
import axios from 'axios'
const { Option } = Select

const mprofile = memo(() => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [userinfo, setuserInfo] = useState({})

  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
    getUserInfo(parseInt(userinfo.userId))
  };
  const handleCancel = () => {
    setIsModalOpen(false);

  };

  const profile = useSelector(state => state.profile)


  const onFinish = (values) => {
    const obj = { Avatar: userinfo.avatar, Nickname: values.nickname, Gender: parseInt(values.gender), Id: parseInt(userinfo.userId) };
    console.log('用户更新数据', obj);
    updateUserInfo(obj).then(res => {
      // console.log(res);
      if (res.data.success) {
        console.log(res);
        messageApi.info('提交成功');
        handleOk();
        returnInfo();

      } else {
        console.log(res);
        messageApi.info(res.data.errorMessage);
        handleOk();
        returnInfo();
      }
      // messageApi.success(response.data.errorMessage ? response.data.errorMessage : '提交成功')
    }).catch(function (error) {
      console.log(error);
    });
  };

  // 回显用户信息
  const returnInfo = (value) => {
    let { userId } = JSON.parse(localStorage.getItem('userInfo'));
    getUserInfo(userId).then(res => {
      console.log(res.data.result);
      setuserInfo(res.data.result);
    })
  }
  const  onChange=function(info) {
    if(info.file.response!==undefined){
      console.log(info)
      console.log(userinfo)
      userinfo.avatar=info.file.response.result
      let obj=userinfo
      setuserInfo({...obj})
      console.log('用户信息',userinfo)
      let params={
        Id:userinfo.userId,
        Nickname:userinfo.nickname,
        Avatar:userinfo.avatar,
        Gender:userinfo.gender
      }
      updateUserInfo(params).then(res=>{
        messageApi.info('更新成功');
        returnInfo()
      })
    }
  }
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const [form] = Form.useForm();

  useEffect(() => {
    let { userId } = JSON.parse(localStorage.getItem('userInfo'));
    console.log(userId);
    getUserInfo(userId).then(res => {
      // console.log(res.data.result);
      setuserInfo(res.data.result);
    })
  }, [])
  return (
    <>
      {contextHolder}
      <div className='mprofile-container'>
        <div className='mprofile'>
          <div className='avatar'>
            <Upload   action={'https://api.codler.cn/api/dfs/upload'} onChange={onChange}>
              <Image className='useimgs' preview={false} src={userinfo.avatar} />
            </Upload>
          </div>
          <div className='nickname'>
            <div>昵称：{userinfo.nickname}</div>
            <div><DesktopOutlined /> 入站4年</div>
          </div>
        </div>
        <div>
          <Button onClick={() => showModal()} block type='primary'>编辑资料</Button>
        </div>
      </div>

      {/* <div className='profile-article'>
        <Card style={{ width: 300 }}>
          <div style={{ textAlign: 'center' }}>已发表文章数</div>
        </Card>
        <Card style={{ width: 300 }}>
          <div style={{ textAlign: 'center' }}>草稿箱</div>
        </Card>
        <Card style={{ width: 300 }}>
          <div style={{ textAlign: 'center' }}>垃圾箱</div>
        </Card>
      </div> */}

      <div className='profile-basic'>
        <Card title={'基础资料'}>
          <div className='account-item'>
            <div>用户昵称</div>
            <div>
              <Button type='link'>
                {userinfo.nickname}
              </Button>
            </div>
          </div>
          <Divider />
          <div className='account-item'>
            <div>用户Id</div>
            <div>
              <Button type='link'>
                {userinfo.userId}
              </Button>
            </div>
          </div>
          <Divider />
          <div className='account-item'>
            <div>用户性别</div>
            <div>
              <Button type='link'>
                {userinfo.gender == 1 ? '男' : '女'}
              </Button>
            </div>
          </div>
          <Divider />
          <div className='account-item'>
            <div>是否为管理员</div>
            <div>
              <Button type='link'>
                {userinfo.isAdmin ? '是' : '否'}
              </Button>
            </div>
          </div>
          <Divider />
          <div className='account-item'>
            <div>注册时间</div>
            <div>
              <Button type='link'>
                {dayjs(userinfo.createTime).format('YYYY年MM月DD日')}
              </Button>
            </div>
          </div>
          <Divider />
        </Card>
      </div>
      <Modal destroyOnClose title="编辑资料" cancelText='取消' okText='关闭' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          name="basic"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="昵称"
            name="nickname"
            rules={[
              {
                required: true,
                message: '请输入昵称!',
              },
            ]}
          >
            <Input placeholder='请输入昵称' />
          </Form.Item>

          {/* <Form.Item
            label="头像"
            name="avatar"
            rules={[
              {
                required: true,
                message: '请输入头像地址!',
              },
            ]}
          >
            <Input placeholder='请输入头像地址' />
          </Form.Item> */}

          <Form.Item
            name="gender"
            label="性别"
            rules={[
              {
                required: true,
                message: '请选择性别!',
              },
            ]}
          >
            <Select placeholder="请选择性别">
              <Option value="1">男</Option>
              <Option value="2">女</Option>
              <Option value="0">未知</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
})

export default mprofile
